package com.topone.service.impl;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.service.WxPayService;
import com.topone.Utils.ServiceUtils;
import com.topone.dataObject.WxServiceProviderNotification;
import com.topone.dto.Pay;
import com.topone.service.NotificationService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class ServiceProvider {

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private NotificationService notificationService;

    public Map<String, String> WxPayService(Pay pay, String openId) {
        Map<String, String> resultMap=new HashMap<>();
        if (Objects.nonNull(pay) && StringUtils.isNotEmpty(openId)) {
            WxPayUnifiedOrderRequest request = WxPayUnifiedOrderRequest
                    .newBuilder()
                    .version("1.0")
                    .deviceInfo("WEB")
                    .body("聚汇－服务商")
                    .detail("")
                    .attach("")
                    .outTradeNo(pay.getOrderId())
                    .feeType("CNY")
                    .totalFee(WxPayUnifiedOrderRequest.yuanToFen((pay.getPrice())))
                    .spbillCreateIp("8.8.8.8")
                    .timeStart("")
                    .timeExpire("")
                    .goodsTag("")
                    .notifyUrl(wxPayService.getConfig().getNotifyUrl())
                    .tradeType(wxPayService.getConfig().getTradeType())
                    .productId("")
                    .limitPay("")
                    .openid(openId)
                    .subOpenid("")
                    .sceneInfo("")
                    .fingerprint("")
                    .build();
            wxPayService.getConfig().setSubAppId(pay.getSubAppId());
            wxPayService.getConfig().setSubMchId(pay.getSubMchId());
            LOG.info("-----支付参数--------{}", ServiceUtils.toJson(request));
            try {
                resultMap = wxPayService.createOrder(request);
                LOG.info("-----预付单--------{}", ServiceUtils.toJson(resultMap));
                WxServiceProviderNotification notification=new WxServiceProviderNotification();
                notification.setOutTradeNo(request.getOutTradeNo());
                notification.setOpenid(openId);
                notification.setPrepayId(resultMap.get("package"));
                notificationService.saveProviderResult(notification);
            } catch (Exception e) {
                LOG.error("获取服务商预付单信息失败,{}", e.getMessage());
            }
        }
        return resultMap;
    }
}
